package client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author by mozping
 * @Classname NettyClientHandler
 * @Description TODO
 * @Date 2019/4/2 19:55
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger LOG = LoggerFactory.getLogger(NettyClientHandler.class);


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("NettyClientHandler channelActive 执行,准备发送数据...");
        String msg = "Are you ok! ";
        ByteBuf byteBuf = ctx.alloc().buffer(4 * msg.length());
        byteBuf.writeBytes(msg.getBytes());
        ctx.write(byteBuf);
        LOG.info("NettyClientHandler channelActive发送数据完毕...");
        ctx.flush();

    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        LOG.info("NettyClientHandler channelRead 执行，准备读取服务端响应数据...");
        ByteBuf byteBuf = (ByteBuf) msg;
        LOG.info("读取到的数据是:{} ", byteBuf.toString(CharsetUtil.UTF_8));
        ctx.close();

    }
}
